package com.yupi.yangoj.judge.codesandbox.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.yupi.yangoj.common.ErrorCode;
import com.yupi.yangoj.exception.BusinessException;
import com.yupi.yangoj.judge.codesandbox.CodeSandBox;
import com.yupi.yangoj.judge.codesandbox.model.ExecuteCodeRequest;
import com.yupi.yangoj.judge.codesandbox.model.ExecuteCodeResponse;
import org.springframework.util.DigestUtils;


/**
 * 远程代码沙箱（提供外部接口访问代码沙箱服务）
 */
public class RemoteCodeSandBoxImpl implements CodeSandBox {

    //代码沙箱安全调用校验
    private static final String AUTH = "auth";
    private static final String SECRET_KEY = DigestUtils.md5DigestAsHex("secretKey".getBytes());


    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        System.out.println("调用远程代码沙箱");
        String url = "http://192.168.159.100:8088/executeCode";    //代码沙箱地址
        String json = JSONUtil.toJsonStr(executeCodeRequest);
        //向代码沙箱发送代码执行请求
        String responseBody = HttpUtil.createPost(url)
                .body(json)
                .header(AUTH, SECRET_KEY)
                .execute()
                .body();

        if (StrUtil.isBlank(responseBody)){
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR,"execute remoteCodeSandbox error,message = " + responseBody);
        }

        //返回调用信息（代码的执行结果）
        ExecuteCodeResponse executeCodeResponse = JSONUtil.toBean(responseBody, ExecuteCodeResponse.class);
        return executeCodeResponse;
    }
}
